<template>
  <view class="container">
			<view class="example">
        <view class="item">
          <view class="itemTitle">地址</view>
          <view class="line" @click="showMap">
            <input class="itemcontent" type="text" placeholder="选择收货地址" v-model="address">
            <image
              class="itemicon"
              src="../../../static/business/togo.png"
            />
          </view>
        </view>
        <view class="item">
          <view class="itemTitle">门牌号</view>
          <view class="line">
            <input type="text" placeholder="详细地址，例1层101室" v-model="detail">
          </view>
        </view>
        <view class="item">
          <view class="itemTitle">收货人</view>
          <view class="line">
            <input type="text" placeholder="请填写收货人姓名" v-model="consignee">
            <view class="choosegender" @click="gender = '先生'">
              <view class="round" :class="{active:gender === '先生',unactive:gender === '女士'}">
                <view :class="{dot:gender === '先生'}"></view>
              </view>
              <view class="text">
                先生
              </view>
            </view>
            <view class="choosegender" @click="gender = '女士'">
              <view class="round" :class="{active:gender === '女士',unactive:gender === '先生'}">
                <view :class="{dot:gender === '女士'}"></view>
              </view>
              <view class="text">
                女士
              </view>
            </view>
          </view>
        </view>
        <view class="item">
          <view class="itemTitle">手机号</view>
          <view class="line">
            <input type="text" placeholder="请输入手机号" v-model="mobile">
          </view>
        </view>
			</view>
      <view class="tochoose" @click="choose = !choose">
        <view class="round" :class="{active:choose,unactive:!choose}">
          <view :class="{dot:choose}"></view>
        </view>
        <view class="text">
          设为默认地址
        </view>
      </view>
      <view>
        <view class="submit" @click="submit">保存</view>
      </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { addAddress, editAddress, addressList } from "@/service/index.ts"
import { onLoad } from "@dcloudio/uni-app"

const addrId = ref()
// 获取地址列表
onLoad((options) => {
  if (!options.id) return
  addrId.value = options.id
  addressList().then(res => {
    address.value = res.find(item => item.id == options.id)?.address
    detail.value = res.find(item => item.id == options.id)?.detail
    consignee.value = res.find(item => item.id == options.id)?.consignee.slice(0, -2)
    mobile.value = res.find(item => item.id == options.id)?.mobile
    choose.value = res.find(item => item.id == options.id)?.is_default
    gender.value = res.find(item => item.id == options.id)?.consignee.slice(-2) == '先生' ? '先生' : '女士'
  })
})

// 设为默认地址
const choose = ref(false)

// 选择性别
const gender = ref('先生')

// 声明基础信息
const address = ref('')
const detail = ref('')
const consignee = ref('')
const mobile = ref('')
const is_default = ref(0)

// 获取微信地址
// 调用地图定位
const showMap = () => {
  wx.getSetting({
    success(res) {
      console.log("res是否开启授权", res);
      if (!res.authSetting["scope.userLocation"]) {
        wx.authorize({
          scope: "scope.userLocation",
          success() {
            // console.log('前用户发起授权请求')
            wx.chooseLocation({
              success: (res) => {
                getValueMap(res);
              },
              fail: (res) => {
                console.log("打开地图选择位置取消", res);
              },
            });
          },
          fail() {
            // 用户点击不允许引导重新获取授权
            fetchAgainLocation();
          },
        });
      } else {
        console.log("已经授权");
        // 已经授权了就会直接进入地图
        wx.chooseLocation({
          success: (res) => {
            getValueMap(res);
          },
          fail: (res) => {
            console.log("打开地图选择位置取消", res);
          },
        });
      }
    },
  });
}
const fetchAgainLocation = () => {
  wx.getSetting({
    success: (res) => {
      var statu = res.authSetting;
      if (!statu["scope.userLocation"]) {
        wx.showModal({
          title: "是否授权当前位置",
          content:
            "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
          success: (tip) => {
            if (tip.confirm) {
              wx.openSetting({
                success: (data) => {
                  if (data.authSetting["scope.userLocation"] === true) {
                    wx.showToast({
                      title: "授权成功",
                      icon: "success",
                      duration: 1000,
                    });
                    wx.chooseLocation({
                      success: (res) => {
                        getValueMap(res);
                      },
                    });
                  } else {
                    wx.showToast({
                      title: "授权失败",
                      icon: "success",
                      duration: 1000,
                    });
                  }
                },
                fail: () => {},
                complete: () => {},
              });
            }
          },
        });
      }
    },
    fail: () => {},
    complete: () => {},
  });
}
const getValueMap = (res) => {
  address.value = res.address
}

// 保存地址
const submit = () => {
  // 判断是否为空
  if (!address.value) {
    wx.showToast({
      title: '请选择收货地址',
      icon: 'none'
    })
    return
  }
  if (!detail.value) {
    wx.showToast({
      title: '请填写详细地址',
      icon: 'none'
    })
    return
  }
  if (!consignee.value) {
    wx.showToast({
      title: '请填写收货人姓名',
      icon: 'none'
    })
    return
  }
  if (!mobile.value) {
    wx.showToast({
      title: '请填写手机号',
      icon: 'none'
    })
    return
  }

  // 判断手机号格式
  if (!/^1[3456789]\d{9}$/.test(mobile.value)) {
    wx.showToast({
      title: '手机号格式错误',
      icon: 'none'
    })
    return
  }

  // 保存地址
  wx.showLoading({
    title: '保存中',
    mask: true
  })
  if(addrId.value) {
    editAddress({
      id: addrId.value,
      mobile: mobile.value,
      address: address.value,
      detail: detail.value,
      consignee: consignee.value + gender.value,
      is_default: choose.value ? 1 : 0
    }).then(() => {
      wx.hideLoading()
      wx.showToast({
        title: '修改成功',
        icon: 'success'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }).catch(err => {
      console.log(err);
      wx.hideLoading()
      wx.showToast({
        title: '修改失败',
        icon: 'none'
      })
    })
    return
  }else {
    addAddress({
      mobile: mobile.value,
      address: address.value,
      detail: detail.value,
      consignee: consignee.value + gender.value,
      is_default: choose.value ? 1 : 0
    }).then(() => {
      wx.hideLoading()
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }).catch(err => {
      console.log(err);
      wx.hideLoading()
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    })
  }
}

</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: $body-bc;
  color: $content-color;
  padding: 16rpx 24rpx 0;

  .example {
		padding: 30rpx 39rpx;
		background: #112959;
    border-radius: 20rpx;
    margin-bottom: 14rpx;
	}
  .tochoose {
    display: flex;
    align-items: center;
    margin-bottom: 97rpx;
    padding-left: 35rpx;
    background: #112959;
    border-radius: 20rpx;
    font-family: FZLanTingHeiS-R-GB;
    font-weight: 400;
    font-size: 26rpx;
    color: #3A75C0;
    line-height: 100rpx;
  }
  .round {
    position: relative;
    width: 36rpx;
    height: 36rpx;
    background: rgba(244,102,38,0);
    border-radius: 50%;
    margin-right: 20rpx;
  }
  .submit {
    margin: 0 79rpx;
    background: url('../../../static/business/order.png') center center no-repeat;
    background-size: 100%;
    width: 560rpx;
    font-family: FZLanTingHeiS-R-GB;
    font-weight: 400;
    font-size: 30rpx;
    color: #00C1FF;
    line-height: 104rpx;
    text-align: center;
  }
  .active {
    border: 1px solid #00BAFF;
  }
  .unactive {
    border: 1px solid #25488E;
  }
  .dot {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 20rpx;
    height: 20rpx;
    background: #00BAFF;
    border-radius: 50%;
  }
}
.item {
  display: flex;
  align-items: center;
  height: 78rpx;
  font-family: FZLanTingHeiS-R-GB;
  font-weight: 400;
  font-size: 28rpx;
  color: #3A75C0;
  line-height: 100rpx;
  .itemTitle {
    margin-right: 30rpx;
    width: 100rpx;
    box-sizing: border-box;
    white-space: nowrap;
  }
  .itemcontent::placeholder {
    font-size: 28rpx;
    color: #3A75C0;
  }
  .itemicon {
    width: 20rpx;
    height: 30rpx;
    margin-right: 15rpx;
  }
}
.line {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 78rpx;
  border-bottom: 1px solid #1D4374;
}
.text {
  white-space: nowrap;
}
.choosegender {
  display: flex;
  height: 75rpx;
  align-items: center;
  background: #112959;
  border-radius: 20rpx;
  font-family: FZLanTingHeiS-R-GB;
  font-weight: 400;
  font-size: 26rpx;
  color: #3A75C0;
  margin: 0 5rpx;
}
</style>
